//
//  CZHookInject.m
//  CZHook
//
//  Created by czera on 2020/4/15.
//  Copyright © 2020 czera. All rights reserved.
//

// hook登录用户名、密码

#import "CZHookInject.h"
#import <objc/runtime.h>

@implementation CZHookInject

/* 添加方法
 +(void)load{
     Method oldMyNext = class_getInstanceMethod(objc_getClass("WCAccountMainLoginViewController"), @selector(onNext));
     
     // 添加新方法
     BOOL didAddMethod = class_addMethod(objc_getClass("WCAccountMainLoginViewController"), @selector(hook_myNext), hook_myNext, @"v@:");

     // 获取新添加的方法
     Method newMethod = class_getInstanceMethod(objc_getClass("WCAccountMainLoginViewController"), @selector(hook_myNext));
     
     method_exchangeImplementations(oldMyNext, newMethod);
 }

 void hook_myNext(id self,SEL _cmd) {

     NSString *userNmaeStr = [[[self valueForKey:@"_textFieldUserNameItem"] valueForKey:@"m_textField"] performSelector:@selector(text)];

     NSLog(@"输入的用户名是：%@",userNmaeStr);

     [self performSelector:hook_myNext];
 }
 */

//TODO: 替换方法
/*
 1.定义一个函数指针，保存之前的函数
 2.获取之前的函数
 3.替换之前的函数
 
 缺点：
 如果你的交换没有onNext方法，使用 replaceMethod 会默认帮你添加一个空方法
 */
/*
IMP (*old_onNext)(id self,SEL _cmd);

+(void)load{
    // 1，拿到原始的imp
    old_onNext = method_getImplementation(class_getInstanceMethod(objc_getClass("WCAccountMainLoginViewController"), @selector(onNext)));
    
    // 替换imp
    class_replaceMethod(objc_getClass(@"WCAccountMainLoginViewController"), @selector(onNext), my_next, @"v@:");
}

void my_next(id self,SEL _cmd){
    NSString *userNameStr = [[[self valueForKey:@"_textFieldUserNameItem"] valueForKey:@"m_textField"] performSelector:@selector(text)];
    NSLog(@"输入的用户名是：%@",userNameStr);
    
    // 调用之前的函数
    old_onNext(self,_cmd);
}
 */

//TODO: setIMP 和 getIMP 方法
/*
 1.拿到旧的方法的IMP
 2.保存旧的IMP
 3.设置IMP
 */
IMP (*old_onNext)(id self,SEL _cmd);

+(void)load{
    // 1.拿到原始的method,以下两句代码效果一样，下面的不会报警告
//    Method onNext = class_getInstanceMethod(objc_getClass("WCAccountMainLoginViewController"), @selector(onNext));
    Method onNext = class_getInstanceMethod(objc_getClass("WCAccountMainLoginViewController"), sel_registerName("onNext"));
    
    // 2.保存旧的IMP
    old_onNext = method_getImplementation(onNext);
    
    // 3.设置IMP
    method_setImplementation(onNext, (IMP)my_next);
}

void my_next(id self,SEL _cmd){
    NSString *userNameStr = [[[self valueForKey:@"_textFieldUserNameItem"] valueForKey:@"m_textField"] performSelector:@selector(text)];
    NSLog(@"输入的用户名是：%@",userNameStr);
    
    // 调用之前的函数
    old_onNext(self,_cmd);
}
@end
